import sys
import importer_v2 as importer
import db
import baostock as bs
from datetime import datetime, timedelta

date_format = "%Y%m%d"

def load_leak_data(sharding, stock_code):
    if(int(sharding) < 10):
        index = '00'+sharding
    else:
        index = '0'+sharding
    sql = "SELECT * FROM (SELECT count(*) as `number`,`date`,stockId as stock_code FROM bao_stock.min5data" + str(index) 
    sql += " where stockId='" + stock_code + "' group by stockId,`date`) a where a.number>49 or a.number<47;"
    rs = None
    with db.UsingMysql() as um:
        um.cursor.execute(sql)
        rs = um.cursor.fetchall()
    return rs

def load_sharding(sharding):
    rs = None
    sql = "select * from sharding where sharding_table=" + sharding
    with db.UsingMysql() as um:
        um.cursor.execute(sql)
        rs = um.cursor.fetchall()
    return rs

def delete_by_day(stock_code, sharding, date_str):
    if(int(sharding) < 10):
        index = '00'+sharding
    else:
        index = '0'+sharding
    date = datetime.strptime(date_str, importer.dateFormat)
    date_str = datetime.strftime(date, date_format)

    sql = "delete from min5data" + index + " where minbasicDataID like '" + date_str + "%' and stockId='" + stock_code + "'"
    with db.UsingMysql() as um:
        um.cursor.execute(sql)

def load(sharding):
    rs = load_sharding(sharding)
    for sharding_data in rs:
        stock_code = sharding_data["stock_code"]
        leak_list = load_leak_data(sharding, stock_code)
        if (len(leak_list) > 0):
            bs.login()
            for data in leak_list:
                delete_by_day(data["stock_code"], sharding, data["date"])
                importer.load_by_code(data["stock_code"], sharding, data["date"], data["date"] , False)   
            bs.logout()

if __name__ == '__main__':
    sharding = ""
    if len(sys.argv) > 1:
        sharding = sys.argv[1]
    load(sharding)
    